package com.fy.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.fy.util.FileUtil;

@WebServlet("/upload")
public class FileUpLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
	IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
		String uploadPath = request.getServletContext().getRealPath("/WEB-INF/upload");
		FileUtil.mkdirs(uploadPath);
		try {
			// 创建文件上传处理工厂
			FileItemFactory factory = new DiskFileItemFactory();
			// 创建文件上传解析器
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			// 监听文件上传进度
			fileUpload.setProgressListener(new ProgressListener() {
				@Override
				public void update(long pBytesRead, long pContentLength, int arg2) {
					System.out.println("文件大小为：" + pContentLength + "，当前已上传：" + pBytesRead);
				}
			});
			// 解决上传文件名的中文乱码
			fileUpload.setHeaderEncoding("UTF-8");
			// 判断提交上来的数据是否是上传表单的数据
			if (!ServletFileUpload.isMultipartContent(request))
				return;// 按照传统方式获取数据
			// 设置上传单个文件的大小的最大值，目前是设置为1024*1024字节，也就是1MB
			// fileUpload.setFileSizeMax(1024*1024);
			// 设置上传文件总量的最大值，最大值=同时上传的多个文件的大小的最大值的和，目前设置为10MB
			// fileUpload.setSizeMax(1024*1024*10);
			// 解析上传文件，得到上传文件的集合，每一个文件对应一个Form表单的输入项
			List<FileItem> files = fileUpload.parseRequest(request);
			for (FileItem item : files) {
				String fileName = FileUtil.makeFileName(item.getName());
				String savePath = FileUtil.makePath(item.getName(), uploadPath);
				if (fileName != null) {
					File file = new File(savePath + "\\" + fileName);
					item.write(file);
				}
			}
			response.getWriter().print("{\"result\":true}");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}